package com.ali.item.controller;

import com.ali.item.entity.ItemCategory;
import com.ali.item.entity.ItemInfo;
import com.ali.item.service.CategoryService;
import com.ali.item.service.ItemService;
import com.ali.item.utils.ResultViewModelUtil;
import com.ali.item.viewmodle.ItemViewModel;
import com.ali.item.viewmodle.ItemInfoViewModel;
import com.ali.item.viewmodle.ResultViewModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName ItemController
 * @Description 商品
 * @Author Alistair.Chow
 * @date 2018/12/14 14:21
 * @Version 1.0
 */
@RestController
@RequestMapping("/item")
public class ItemController {
    @Autowired
    private ItemService itemService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResultViewModel<ItemViewModel> list(){
        //1. 查询所有在架商品
        List<ItemInfo> itemInfoList = itemService.findValidItemAll();
        //2. 获取类目ID列表
        List<Integer> categoryIdList = itemInfoList.stream()
                .map(ItemInfo::getCategoryId)
                .collect(Collectors.toList());
        //3. 根据类目ID列表从数据库查询类目
        List<ItemCategory> categoryList = categoryService.findAllByIdIn(categoryIdList);

        //4. 构造数据
        List<ItemViewModel> itemViewModelList = new ArrayList<>();
        for(ItemCategory itemCategory: categoryList){
            ItemViewModel itemViewModel = new ItemViewModel();
            itemViewModel.setCategoryName(itemCategory.getName());
            itemViewModel.setCategoryId(itemCategory.getId());

            List<ItemInfoViewModel> itemInfoViewModelList = new ArrayList<>();
            for(ItemInfo itemInfo: itemInfoList){
                if(itemInfo.getCategoryId().equals(itemCategory.getId())) {
                    ItemInfoViewModel itemInfoViewModel = new ItemInfoViewModel();
                    itemInfoViewModel.setItemName(itemInfo.getName());
                    itemInfoViewModel.setItemId(itemInfo.getId());
                    itemInfoViewModelList.add(itemInfoViewModel);
                }
            }
            itemViewModel.setItemInfoViewModelList(itemInfoViewModelList);
            itemViewModelList.add(itemViewModel);
        }

        return ResultViewModelUtil.success(itemViewModelList);
    }

    /**
    * @Author Alistair.Chow
    * @Description 获取商品列表
    * @Date 15:31 2018/12/29
    * @Param [productIdList]
    * @return java.util.List<ItemInfo>
    **/
    @PostMapping("/listForOrder")
    public List<ItemInfo> listForOrder(@RequestBody List<Integer> idList){
        return itemService.findList(idList);
    }
}
